<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能门窗传感器状态</title>
    <script src="../../static/js/chart-3.7.0.min.js"></script>
    <script src="../../static/js/chartjs-plugin-zoom.min.js"></script>
    <style>
        body {
            font-family: 'Helvetica Neue', Helvetica, Arial, sans-serif;
            margin: 0;
            padding: 1em;
            background-color: #f9f9f9;
        }

        h1 {
            text-align: center;
            color: #333;
        }

        .container {
            max-width: 960px;
            margin: auto;
        }

        .section {
            background: #fff;
            border-radius: 12px;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            padding: 1.5em;
            margin-bottom: 1.5em;
        }

        .section h2 {
            margin-top: 0;
        }

        .status-text {
            font-size: 1.2em;
            color: #007acc;
        }

        .controls {
            margin-top: 1em;
            text-align: right;
        }

        input[type=number] {
            width: 70px;
            padding: 6px;
            margin-left: 6px;
        }

        canvas {
            margin-top: 1em;
            width: 100% !important;
            height: 300px !important;
        }

        @media (max-width: 600px) {
            .controls {
                text-align: left;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <h1>温湿度状态监控</h1>

    <div class="section" id="online-status">
        <h2>模块在线状态</h2>
        <div class="status-text" id="moduleStatus">加载中...</div>
    </div>

    <div class="section">
        <h2>传感器数据展示</h2>
        <div class="controls">
            显示最近 <input type="number" id="jtCount" value="5" min="1" max="100"> 条数据
            <button id="refreshBtn">刷新</button>
        </div>
        <canvas id="dsChart"></canvas>
        <canvas id="tempChart"></canvas>
        <canvas id="humiChart"></canvas>
    </div>
</div>

<script>
    const moduleId = 3;
    const deviceIds = {
        ds: 1,
        dht_temp: 7,
        dht_humi: 10
    };

    const baseURL = location.protocol === 'https:' ? 'https://iot.jimo.fun' : 'http://iot.jimo.fun';

    async function fetchModuleStatus() {
        const res = await fetch(`/module/times?moduleId=${moduleId}`);
        const data = await res.json();
        document.getElementById("moduleStatus").textContent = data.data || "无数据";
    }

    async function fetchSensorData(deviceId, count) {
        const res = await fetch(`/device/logs?deviceId=${deviceId}&jt=${count}`);
        return await res.json();
    }

    let chartInstances = {};

    function renderChart(data, canvasId, label) {
        const ctx = document.getElementById(canvasId).getContext('2d');
        const labels = data.map(d => new Date(d.time).toLocaleTimeString());
        const values = data.map(d => parseFloat(d.value));

        if (chartInstances[canvasId]) {
            chartInstances[canvasId].destroy();
        }

        chartInstances[canvasId] = new Chart(ctx, {
            type: 'line',
            data: {
                labels: labels,
                datasets: [{
                    label: label,
                    data: values,
                    borderColor: '#007acc',
                    backgroundColor: 'rgba(0, 122, 204, 0.1)',
                    fill: true,
                    tension: 0.2,
                    pointRadius: 4,
                    pointHoverRadius: 6
                }]
            },
            options: {
                responsive: true,
                plugins: {
                    tooltip: {
                        enabled: true,
                        callbacks: {
                            label: function (context) {
                                return `${label}: ${context.raw}`;
                            }
                        }
                    },
                    legend: {
                        display: true
                    },
                    zoom: {
                        pan: {
                            enabled: true,
                            mode: 'x'
                        },
                        zoom: {
                            wheel: {
                                enabled: true
                            },
                            pinch: {
                                enabled: true
                            },
                            mode: 'x'
                        }
                    }
                },
                scales: {
                    y: {
                        beginAtZero: false
                    }
                }
            }
        });
    }

    async function loadAllSensorData() {
        const jt = document.getElementById("jtCount").value;
        const [ds, temp, humi] = await Promise.all([
            fetchSensorData(deviceIds.ds, jt),
            fetchSensorData(deviceIds.dht_temp, jt),
            fetchSensorData(deviceIds.dht_humi, jt)
        ]);

        renderChart(ds, "dsChart", "DS18B20 温度 (℃)");
        renderChart(temp, "tempChart", "DHT11 温度 (℃)");
        renderChart(humi, "humiChart", "DHT11 湿度 (%RH)");
    }

    document.getElementById("refreshBtn").addEventListener("click", loadAllSensorData);

    fetchModuleStatus();
    loadAllSensorData();
</script>
</body>
</html>
